import { defineComponent, ref, watch } from "vue";
import { Modal, Form, Input, message } from "ant-design-vue";
import { user } from "@/api";
import styles from "./change-password/index.module.less";

interface PropInterface {
  open: boolean;
  onCancel: () => void;
}

export default defineComponent({
  name: "ChangePasswordModel",
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    onCancel: {
      type: Function,
      required: true,
    },
  },
  setup(props: PropInterface) {
    const form = ref();
    const loading = ref(true);

    watch(
      () => props.open,
      (newVal) => {
        if (newVal) {
          form.value?.setFieldsValue({
            old_password: "",
            new_password: "",
            again_new_password: "",
          });
        }
      }
    );

    const onFinish = (values: any) => {
      if (values.again_new_password !== values.new_password) {
        message.error("再次输入的新密码错误");
        return;
      }
      user.password(values.old_password, values.new_password).then((res: any) => {
        message.success("保存成功！");
        props.onCancel();
      });
    };

    const onFinishFailed = (errorInfo: any) => {
      console.log("Failed:", errorInfo);
    };

    return () => (
      <>
        {props.open ? (
          <Modal title="修改密码" cancelText={"取消"} okText={"确定"} centered forceRender open={true} width={416} onOk={() => form.value?.submit()} onCancel={() => props.onCancel()} maskClosable={false}>
            <div class="float-left mt-24">
              <Form ref={form} name="change-password" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} onFinish={onFinish} onFinishFailed={onFinishFailed}>
                <Form.Item label="请输入原密码" name="old_password" rules={[{ required: true, message: "请输入原密码!" }]}>
                  <Input.Password style={{ width: 200 }} autocomplete="off" placeholder="请输入原密码" />
                </Form.Item>
                <Form.Item label="输入新密码" name="new_password" rules={[{ required: true, message: "请输入新密码!" }]}>
                  <Input.Password style={{ width: 200 }} autocomplete="off" placeholder="请输入新密码" />
                </Form.Item>
                <Form.Item label="再次输入新密码" name="again_new_password" rules={[{ required: true, message: "再次输入新密码!" }]}>
                  <Input.Password style={{ width: 200 }} autocomplete="off" placeholder="再次输入新密码" />
                </Form.Item>
              </Form>
            </div>
          </Modal>
        ) : null}
      </>
    );
  },
});
